package org.chnxi.study.concurrent.future;

import java.util.concurrent.*;

public class FutureTaskDemo {

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        FutureTask<Integer> task = new FutureTask<Integer>(()->{
            System.out.println("子线程开始执行");
            int num = (int) (Math.random() * 1000);
            try {
                TimeUnit.MILLISECONDS.sleep(num);
                if (num % 2 == 0) {
                    //异常就会被包装成ExecutionException异常抛出。
                    throw new RuntimeException("模拟异常发生");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return num;
        });

        //task.run();
        executorService.submit(task);

        TimeUnit.MILLISECONDS.sleep(1);

        System.out.println("已经发送执行任务，主线程可继续执行。。。");
        try {
            Integer result = task.get();
            System.out.println("获取到执行结果："+result);
        } catch (InterruptedException e) {
            System.out.println("InterruptedException>>>"+e.getMessage());
        } catch (ExecutionException e) {
            System.out.println("ExecutionException>>>"+e.getMessage());
        } finally {
            executorService.shutdown();
        }

    }

}
